package com.haircut.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.haircut.base.Result;
import com.haircut.mapper.WechatUser;
import com.haircut.model.dto.UserDTO;
import com.haircut.security.model.WxLoginRequest;
import com.haircut.security.model.WxLoginResult;
import com.haircut.security.model.WxUpdateUserInfoRequest;
import com.haircut.security.util.SecurityUtils;
import com.haircut.service.WechatUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.haircut.utils.CommUtil.checkProductionEnvironment;

@RestController
@RequestMapping("/api/v1/auth")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "微信登录接口")
public class WechatLoginController {

    private final WxMaService wxMaService;

    @Value("${wechat.miniapp.appid}")
    private String appid;
    private final WechatUserService wechatUserService;

    @Operation(summary = "微信登录")
    @PostMapping("/wxlogin")
    public Result<WxLoginResult> wxlogin(
            @Parameter(description = "请求对象", example = "xxxxxx") @RequestBody WxLoginRequest request
    ) throws WxErrorException {
        if ((!ObjectUtils.isEmpty(request.getDebug())) && request.getDebug()) {
            Boolean isProdEnv = checkProductionEnvironment();
            if (!isProdEnv) {
                WxLoginResult loginResult = wechatUserService.loginByWechat("", request.getWxOpenid());
                return Result.success(loginResult);
            }
        }

        String code = request.getCode();
        if (StringUtils.isBlank(code)) {
            Result.failed("empty jscode");
        }

        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(request.getPhoneCode());
            log.info("sessionkey{}",session.getSessionKey());
            log.info("phoneNoInfo{}", JSONUtil.toJsonStr(phoneNoInfo));
            log.info("Openid{}",session.getOpenid());
            WxLoginResult loginResult = wechatUserService.loginByWechat(phoneNoInfo.getPhoneNumber(), session.getOpenid());
            //TODO 可以增加自己的逻辑，关联业务相关数据
            //return JsonUtils.toJson(session);
            return Result.success(loginResult);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return Result.failed(e.toString());
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
    }
        @Operation(summary = "微信登出")
        @PostMapping("/wxloginOut")
        public Result<WxLoginResult> wxloginOut(
    )  {
            return Result.success();
    }



    @Operation(summary = "用户信息")
    @GetMapping("/userInfo")
    public Result<UserDTO> userInfo(
    )  {
        Long userId = SecurityUtils.getUser().getUserId();
        WechatUser userModel = wechatUserService.getById(userId);
        UserDTO user = new UserDTO();
        BeanUtil.copyProperties(userModel, user);
        user.setName(userModel.getNickname());
        return Result.success(user);
    }

    @Operation(summary = "更新微信用户昵称头像")
    @PostMapping("/updateUserInfo")
    public Result updateUserInfo( @RequestBody WxUpdateUserInfoRequest wxLoginRequest
    ) throws WxErrorException {
        Long userId = SecurityUtils.getUser().getUserId();
        WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(wxLoginRequest.getCode());
        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(session.getSessionKey(), wxLoginRequest.getEncryptedData(), wxLoginRequest.getIvStr());
        wechatUserService.updateUserInfo(userId,userInfo.getAvatarUrl(),userInfo.getNickName());
        return Result.success();
    }
    @Operation(summary = "用户信息")
    @GetMapping("/userInfoByPhone")
    public Result<UserDTO> userInfoByPhone(
            String phone
    )  {
        Long userId = SecurityUtils.getUser().getUserId();
        WechatUser userModel = wechatUserService.getByPhone(phone);
        UserDTO user = new UserDTO();
        BeanUtil.copyProperties(userModel, user);
        user.setName(userModel.getNickname());
        return Result.success(user);
    }

}